package com.diu.domain.strategy.service.rule.filter.factory;

import com.diu.domain.strategy.model.entity.RuleActionEntity;
import com.diu.domain.strategy.service.annotation.LogicStrategy;
import com.diu.domain.strategy.service.rule.filter.ILogicFilter;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author #diu
 * @description #默认规则工厂
 * @create #2025/10/10 15:38
 */
@Component
public class DefaultLogicFactory {
    // 根据过滤器模式名称，存储对应的过滤器实现类
    public Map<String, ILogicFilter<?>> logicFilterMap = new ConcurrentHashMap<>();
    // Spring会自动把容器中所有实现了ILogicFilter接口的Bean注入到logicFilters列表中
    // 因为只有一个有参构造方法，所以会自动注入
    public DefaultLogicFactory(List<ILogicFilter<?>> logicFilters) {
        logicFilters.forEach(logic -> {
            LogicStrategy strategy = AnnotationUtils.findAnnotation(logic.getClass(), LogicStrategy.class);
            if (null != strategy) {
                logicFilterMap.put(strategy.logicMode().getCode(), logic);
            }
        });
    }
    // 对外提供获取过滤器实现类的接口
    public <T extends RuleActionEntity.RaffleEntity> Map<String, ILogicFilter<T>> openLogicFilter() {
        return (Map<String, ILogicFilter<T>>) (Map<?, ?>) logicFilterMap;
    }

    @Getter
    @AllArgsConstructor
    public enum LogicModel {

        RULE_WIGHT("rule_weight","【抽奖前规则】根据抽奖权重返回可抽奖范围KEY","raffle_before"),
        RULE_BLACKLIST("rule_blacklist","【抽奖前规则】黑名单规则过滤，命中黑名单则直接返回","raffle_before"),
        RULE_WHITELIST("rule_whitelist","【抽奖前规则】白名单规则过滤，命中白名单则直接放行","raffle_before"),
        RULE_LOCK("rule_lock","【抽奖中规则】锁定规则，用户抽奖n次后，对应奖品可解锁抽奖","raffle_middle"),
        RULE_LUCK_AWARD("rule_luck_award","【抽奖后规则】幸运奖规则，用户未中奖时，按概率补偿发放奖品","raffle_after")
        ;

        private final String code;
        private final String info;
        private final String type;

        public static boolean isMiddle(String code){
            return "raffle_middle".equals(LogicModel.valueOf(code.toUpperCase()).type);
        }

        public static boolean isAfter(String code){
            return "raffle_after".equals(LogicModel.valueOf(code.toUpperCase()).type);
        }

    }

}
